<template>
  <div>
    <el-card class="box-card">
      <el-form :inline="true" class="form-container" :model="configForm" ref="queryForm">
        <div class="search">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
                filterable
                remote
                :remote-method="getCustomers"
                :loading="loading"
                v-model="configForm.customerId"
                placeholder="请输入客户名称"
            >
              <el-option
                  v-for="item in customerOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="施工地址" prop="engineerProjectId">
            <el-select
                v-model="configForm.engineerProjectId"
                placeholder="请选择施工地址"
                @change="initTable"
            >
              <el-option
                  v-for="item in engineerProjectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="exportExcel">导出</el-button>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="setMainDisCountRate">设置折扣率</el-button>
        </div>
        <div class="func">
          <el-button icon="el-icon-plus" type="primary" @click="handleCategoryAdd">添加</el-button>
        </div>
      </el-form>
      <div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic
                group-separator=","
                :precision="2"
                :value="Number.isNaN(configForm.mainTotalPrice)?0:configForm.mainTotalPrice"
                title="主材合计"
            >
              <template slot="prefix">
                <i class="el-icon-thumb" style="color: red"></i>
              </template>
              <template slot="suffix">
                <i class="el-icon-thumb" style="color: blue"></i>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
                group-separator=","
                :precision="2"
                :value="configForm.mainFinalPrice"
                title="主材折后"
            >
              <template slot="prefix">
                <i class="el-icon-star-on" style="color: red"></i>
              </template>
              <template slot="suffix">
                <i class="el-icon-star-on" style="color: blue"></i>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
                group-separator=","
                :precision="2"
                :value="configForm.lightTotalPrice"
                title="轻辅合计"
            >
              <template slot="prefix">
                <i class="el-icon-s-flag" style="color: red"></i>
              </template>
              <template slot="suffix">
                <i class="el-icon-s-flag" style="color: blue"></i>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
                group-separator=","
                :precision="2"
                :value="configForm.contactPrice"
                title="最终合同额"
            >
              <template slot="prefix">
                <i class="el-icon-s-flag" style="color: red"></i>
              </template>
              <template slot="suffix">
                <i class="el-icon-s-flag" style="color: blue"></i>
              </template>
            </el-statistic>
          </el-col>
        </el-row>

      </div>

    </el-card>
    <!--  主材分类-->
    <MainCategory @addCategory="addCategory" :mainBudgetId="this.configForm.mainBudgetId"></MainCategory>
    <!--  主材分类表-->
    <el-table
        :data="mainBudget"
        style="width: 100%"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <div style="width: 100%">
            <el-table
                :data="props.row.budgetUnits"
                border
                height="350"
            >
              <el-table-column
                  prop="projectName"
                  label="项目名称"
              >
              </el-table-column>
              <el-table-column
                  prop="brand"
                  label="品牌"
              >
                <template slot-scope="scope">
                  <span>{{ brandMap.get(scope.row.brand) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                  prop="specification"
                  label="规格"
              >
              </el-table-column>
              <el-table-column
                  prop="model"
                  label="型号"
              >
              </el-table-column>
              <el-table-column
                  prop="salePrice"
                  label="销售价"
              >
              </el-table-column>
              <el-table-column
                  prop="num"
                  label="数量"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.num"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                  prop="unit"
                  label="单位"
              >
                <template slot-scope="scope">
                  <span>{{ unitMap.get(scope.row.unit) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                  prop="totalPrice"
                  label="合计"
              >
                <template slot-scope="scope">
                  <span>{{scope.row.num*scope.row.salePrice}}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          width="180"
      >
        <template slot-scope="scope">
          <el-button type="success" circle icon="el-icon-plus" size="mini" @click="handleAddMainMaterial(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column
          prop="name"
          label="分类名称"
          width="180"
      >
      </el-table-column>
      <el-table-column
          label="小计"
          width="180"
      >
        <template slot-scope="scope">
          <span>{{ handleTotalPrice(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="description"
          :show-overflow-tooltip="true"
          label="施工说明"
      >
      </el-table-column>

    </el-table>
    <!--  主材-->
    <MainMaterial
        :brandOptions="brandOptions"
        :brandMap="brandMap"
        :unitMap="unitMap"
        @addMainMaterial="addMainMaterial"
    ></MainMaterial>
    <!--    设置折扣率-->
    <el-dialog
        title="设置折扣率"
        :visible.sync="mainDisCountShow"
        width="20%"

    >
      <el-form :inline="true" class="form-container" :model="mainDisCountForm" ref="disCountForm">
        <el-form-item label="折扣率" prop="discountRate">
          <el-input-number v-model="mainDisCountForm.mainDiscountRate" :precision="2" :step="0.01" :max="1" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="mainDisCountShow = false;mainDisCountForm.mainDiscountRate=''">取 消</el-button>
          <el-button type="primary" @click="saveDiscount">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import MainCategory from '@/views/budgetManagement/MainCategory.vue'
import MainMaterial from '@/views/budgetManagement/MainMaterial.vue'
import { listBrand } from '@/api/brand'
import { listUnit } from '@/api/unit'
import { getCustomer, listAllCustomer, listCustomer } from '@/api/intendedCustomer'
import { listEngineerProjects } from '@/api/engineerProject'
import { getMainBudget, saveMainBudget, setMainDiscountRate } from '@/api/mainBudget'
import { getDiscountPrice, getDiscountRate } from '@/api/budget'

export default {
  name: 'MainBudget',
  components: { MainCategory, MainMaterial },
  props: ['budgetConfig'],
  data() {
    return {
      mainDisCountShow: false,
      mainDisCountForm: {
        id: '',
        mainDiscountRate:''
      },
      configForm: {
        mainTotalPrice: '',
        mainFinalPrice: '',
        lightTotalPrice: '',
        contactPrice: '',
        customerId: '',
        engineerProjectId: '',
        mainBudgetId:'',
        mainDiscountRate:''
      },
      loading: false,
      customerOptions: [],
      engineerProjectOptions: [],
      mainBudget: [],
      brandOptions: [],
      brandMap: new Map(),
      unitMap: new Map()
    }
  },
  watch: {
    'configForm': {
      deep: true,
      handler() {
        this.configForm.contactPrice=this.configForm.mainFinalPrice + this.configForm.lightTotalPrice
        this.configForm.mainFinalPrice=this.configForm.mainTotalPrice*this.mainDisCountForm.mainDiscountRate
      }
    },
    'mainBudget': {
      deep: true,
      handler(newVal) {
        let totalPrice = 0
        newVal.forEach(n => {
          let budgetUnits = n.budgetUnits
          if (budgetUnits) {
            totalPrice += budgetUnits.reduce((prev, cur) => {
              return prev * 1 + cur.salePrice * (cur.num ? cur.num : 0)
            }, 0)
          }
        })
        //主材合计
        this.configForm.mainTotalPrice = totalPrice


      }
    },
    'configForm.customerId'(newVal) {
      listEngineerProjects(newVal).then(data => {
        this.loading = false
        if (data.length > 0) {
          this.engineerProjectOptions = data.map(n => {
            return {
              value: n.id,
              label: n.address
            }
          })
        }
      })
    },
    'configForm.engineerProjectId':{
      deep: true,
      handler(newVal) {
        if (Number.isInteger(newVal)) {
          getDiscountRate(newVal).then(n=>{
            this.mainDisCountForm.id = this.configForm.engineerProjectId
            this.mainDisCountForm.mainDiscountRate = n.mainDiscountRate
          })
          this.loadLightDiscountPrice()
        }
      }
    }
  },
  methods: {
    exportExcel() {
      if (this.configForm.customerId && this.configForm.customerId) {
        const fileUrl = `/api/mainbudget/exportMainBudget/${this.configForm.customerId}/${this.configForm.engineerProjectId}`
        const link = document.createElement('a')
        link.href = fileUrl
        link.setAttribute('download', '主材代购单.xlsx')
        link.click()

      } else {
        this.$message({
          type: 'error',
          message: '请选择客户和项目再导出!'
        })
      }
    },
    saveDiscount() {
      setMainDiscountRate(this.mainDisCountForm).then(()=>{
        this.$message({
          type: 'success',
          message: '保存成功!'
        })
        this.configForm.mainDiscountRate=this.mainDisCountForm.mainDiscountRate
        this.configForm.mainFinalPrice= this.configForm.mainTotalPrice*  this.configForm.mainDiscountRate
        this.mainDisCountShow = false
      })
    },
    setMainDisCountRate() {
      if (this.configForm.engineerProjectId) {
        this.mainDisCountShow = true
        this.mainDisCountForm.id=this.configForm.engineerProjectId
      } else {
        this.$message({
          type: 'error',
          message: '请先选择施工地址!'
        })
      }
    },
    save() {

      this.mainBudget.forEach(n=>{
        if (n.budgetUnits) {
          n.budgetUnits.forEach(k=>{
            k.mainMaterialId=k.id
            k.id = ''
          })
        }
      })
      let data= {
        mainBudgetId: this.configForm.mainBudgetId,
        engineerProjectId: this.configForm.engineerProjectId,
        customerId:this.configForm.customerId,
        items:this.mainBudget
      }
      saveMainBudget(data).then(()=>{
          this.$message({
            type: 'success',
            message:'保存成功'
          })
      })
    },
    initTable() {
      this.loadMainBudget()
    },
    loadEngineerProjects(val) {
      listEngineerProjects(val).then(data => {
        this.loading = false
        if (data.length > 0) {
          this.engineerProjectOptions = data.map(n => {
            return {
              value: n.id,
              label: n.address
            }
          })
        }
      })
    },
    loadCustomer(val) {
      listCustomer(val).then(data => {
        this.loading = false
        if (data.length > 0) {
          this.customerOptions = data.map(n => {
            return {
              value: n.id,
              label: n.name
            }
          })
        }
      })
    },
    getCustomers(val) {
      if (!val) {
        return
      }
      this.loading = true
      this.loadCustomer(val)
      this.configForm.engineerProjectId=''

    },
    handleTotalPrice(row) {
      let budgetUnits = row.budgetUnits
      if (budgetUnits) {
        let totalPrice = budgetUnits.reduce((prev, cur) => {
          return prev * 1 + cur.salePrice * (cur.num ? cur.num : 0)
        }, 0)
        return Number.isNaN(totalPrice) ? '' : totalPrice
      }
    },
    addMainMaterial(category, mainMaterials) {
      let c = this.mainBudget.filter(n => n.id === category)
      if (c.length >= 1) {
        this.$set(c[0], 'budgetUnits', mainMaterials)
      }
    },
    handleCategoryAdd() {
      if (Number.isInteger(this.configForm.customerId) && Number.isInteger(this.configForm.engineerProjectId)) {
        this.$bus.$emit('handleCategoryAdd')
      }
    },
    addCategory(categorys) {
      let cacheMap = new Map()
      this.mainBudget.forEach(n => {
        cacheMap.set(n.id,n.budgetUnits)
      })
      categorys.forEach(n=>{
        let budgetUnits = cacheMap.get(n.id)
        if (budgetUnits) {
          n.budgetUnits = budgetUnits
        }else {
          //清除分类缓存
          this.$bus.$emit('clearCache',n.id)
        }
      })
      this.mainBudget = categorys
    },
    handleAddMainMaterial(id) {
      this.$bus.$emit('handleAddMainMaterial', id)
    },
    loadBasicData() {
      if (this.budgetConfig) {

        this.configForm.customerId = this.budgetConfig.customerId
        getCustomer(this.budgetConfig.customerId).then(data => {
          if (data) {
            this.customerOptions.push(
                {
                  value: data.id,
                  label: data.name
                }
            )

          }
        })
        this.configForm.engineerProjectId = this.budgetConfig.engineerProjectId
        this.loadEngineerProjects(this.configForm.customerId)
      }
      listBrand().then(data => {
        data.forEach(n => {
          this.brandMap.set(n.id, n.name)
        })
        this.brandOptions = data.map(n => {
          return {
            value: n.id,
            label: n.name
          }
        })
      })
      listUnit().then(data => {
        data.forEach(n => {
          this.unitMap.set(n.id, n.name)
        })
      })

    },
    loadMainBudget() {
      if (Number.isInteger(this.configForm.customerId) && Number.isInteger(this.configForm.engineerProjectId)) {
        let data = {
          customerId: this.configForm.customerId,
          engineerProjectId: this.configForm.engineerProjectId
        }
        getMainBudget(data).then(n => {
          if (n) {
            this.configForm.mainBudgetId = n.mainBudgetId
            this.mainBudget = n.items
            this.$bus.$emit('handleCache', n.items)
          } else {
            this.configForm.mainBudgetId = ''
            this.mainBudget = []
          }
        })
      }
    },
    loadLightDiscountPrice() {
      getDiscountPrice(this.configForm).then(n=>{
        this.configForm.lightTotalPrice = n
      })
    }
  },
  mounted() {
    this.loadBasicData()
    this.loadMainBudget()


  }
}
</script>

<style scoped>
.table_container {
  display: flex;
  align-items: center;
}

.button_group {
  margin: 0 20px;

}

.form-container {
  display: flex;
  justify-content: space-between;
}

.reset_btn {
  background-color: #722ed1;
  border: 1px solid #722ed1;
}

.reset_btn:hover {
  background-color: #7849b7;
  border: 1px solid #7849b7;
}

.reset_btn:focus {
  background-color: #7849b7;
  border: 1px solid #7849b7;
}
</style>
